package domain;

import java.util.HashSet;
import java.util.Set;

public class Contact {

	private String firstName;
	private String lastName;
	private String email;
	private long id;
	private long version;
	
	private Set<ContactGroup> books;
    private Set<PhoneNumber> phones;
    private Address address;
    
    public Contact() {
		books = new HashSet<ContactGroup>();
		phones = new HashSet<PhoneNumber>();
	}
    
    public Contact(String firstName, String lastName, String email, Set<ContactGroup> books, Set<PhoneNumber> phones, Address address) {
		books = new HashSet<ContactGroup>();
		phones = new HashSet<PhoneNumber>();
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
		this.books = books;
		this.phones = phones;
		this.address = address;
	}

	public String getEmail(){
		return email;
	}
	
	public void setEmail(String email){
		this.email = email;
	}
	
	public String getFirstName(){
		return firstName;
	}
	
	public void setFirstName(String firstname){
		this.firstName = firstname;
	}
	
	public String getLastName(){
		return lastName;
	}
	
	public void setLastName(String lastname){
		this.lastName = lastname;
	}
	
	public long getId(){
		return id;
	}
	
	public void setId(long id){
		this.id = id;
	}

	public Set<PhoneNumber> getPhones() {
		return phones;
	}

	public void setPhones(Set<PhoneNumber> phones) {
		this.phones = phones;
	}

	public Set<ContactGroup> getBooks() {
		return books;
	}

	public void setBooks(Set<ContactGroup> books) {
		this.books = books;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}
		
	public void addBook(ContactGroup book){
		boolean exists = false;
		for(ContactGroup group : getBooks()){
			if(group.getGroupName().equals(book.getGroupName())){
				exists = true;
				break;
			}
		}
		if(!exists)
			getBooks().add(book);
		
		exists = false;
		for(Contact contact : book.getContacts()){
			if(getId() == contact.getId()){
				exists = true;
				break;
			}
		}
		if(!exists)
			book.getContacts().add(this);
	}
	
	public void removeBook(ContactGroup book){
		ContactGroup cgtmp = null;
		for(ContactGroup group : getBooks()){
			if(group.getGroupName().equals(book.getGroupName())){
				cgtmp = group;
			}
		}
		if(getBooks().contains(cgtmp))
			getBooks().remove(cgtmp);
		
		Contact ctmp = null;
		for(Contact c : book.getContacts()){
			if(getId() == c.id){
				ctmp = c;
			}
		}
		if(book.getContacts().contains(ctmp))
			book.getContacts().remove(ctmp);
	}
	
	public void addPhone(PhoneNumber phone){
		getPhones().add(phone);
		phone.setContact(this);
	}
}
